package dk.sdu.flexibus.addressvalidator;

import java.util.HashSet;

import android.content.Context;
import android.text.Editable;
import android.text.TextWatcher;

public class AddressValidator implements TextWatcher {

	HashSet<AddressValidationListener> validationListeners = new HashSet<AddressValidationListener>();
	Context context;
	private double lowerLeftLatitude;
	private double lowerLeftLongitude;
	private double upperRightLatitude;
	private double upperRightLongitude;
	
	

	public void subscribeAddressValidations(AddressValidationListener listener) {
		validationListeners.add(listener);
	}

	public void unsubscribeAddressValidations(AddressValidationListener listener) {
		validationListeners.remove(listener);
	}

	public AddressValidator(Context context, double lowerLeftLatitude,
			double lowerLeftLongitude, double upperRightLatitude,
			double upperRightLongitude) {
		this.context = context;
		this.lowerLeftLatitude = lowerLeftLatitude;
		this.lowerLeftLongitude = lowerLeftLongitude;
		this.upperRightLatitude = upperRightLatitude;
		this.upperRightLongitude = upperRightLongitude;
	}

	@Override
	public void afterTextChanged(Editable editable) {
		String input = editable.toString();
		(new GeocodingTask(context, this, lowerLeftLatitude,
				lowerLeftLongitude, upperRightLatitude, upperRightLongitude))
				.execute(new String[] { input });
	}

	public void notifyValidationListeners(String input, boolean result) {
		for (AddressValidationListener a : validationListeners) {
			a.addressValidated(result, input);
		}
	}

	@Override
	public void beforeTextChanged(CharSequence arg0, int arg1, int arg2,
			int arg3) {
		// Do nothing....
	}

	@Override
	public void onTextChanged(CharSequence s, int start, int before, int count) {
		// Do nothing....
	}
}
